//go:build !windows
// +build !windows

package iptables

import (
	"encoding/binary"
	"net"
	"os"
	"syscall"
)

const SO_ORIGINAL_DST = 80

func RawAddrFromConn(conn net.Conn) (*net.TCPAddr, bool) {
	var tcpConn *net.TCPConn
	tcpConn, _ = conn.(*net.TCPConn)

	var file *os.File
	file, _ = tcpConn.File()
	fd := file.Fd()
	defer file.Close()

	if ipv6Mreq, err := syscall.GetsockoptIPv6Mreq(int(fd), syscall.SOL_IP, SO_ORIGINAL_DST); err == nil {
		ip := net.IP(ipv6Mreq.Multiaddr[4:8])
		// 所以2:4是sin_port字段。也就是大端字节序的端口
		port := int(binary.BigEndian.Uint16(ipv6Mreq.Multiaddr[2:4]))

		return &net.TCPAddr{
			IP:   ip,
			Port: port,
		}, true
	}

	return nil, false
}
